<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small">
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="success" icon="el-icon-microphone" size="mini" @click="goToVoiceToText">语音转文字</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div>
            <el-button type="primary" icon="Plus" @click="handleAdd">新增</el-button>
            <el-button type="danger" icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
            <el-button type="warning" icon="Upload" @click="handleImport">导入</el-button>
            <el-button type="success" icon="Download" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>
      
      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="50" />
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="用户名" prop="username" min-width="120" show-overflow-tooltip />
        <el-table-column label="昵称" prop="nickname" min-width="120" show-overflow-tooltip />
        <el-table-column label="邮箱" prop="email" min-width="150" show-overflow-tooltip />
        <el-table-column label="手机号" prop="phone" width="120" show-overflow-tooltip />
        <el-table-column label="用户类型" prop="userType" width="100">
          <template #default="scope">
            <el-tag :type="getUserTypeTag(scope.row.userType)">
              {{ getUserTypeLabel(scope.row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === '0' ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleView(scope.row)">查看</el-button>
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="管理员" value="01" />
            <el-option label="经销商" value="02" />
            <el-option label="客户" value="03" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.userId">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 查看用户对话框 -->
    <el-dialog title="查看用户详情" v-model="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ viewForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ viewForm.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ viewForm.nickname }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ viewForm.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ viewForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="用户类型">
          <el-tag :type="getUserTypeTag(viewForm.userType)">
            {{ getUserTypeLabel(viewForm.userType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewForm.status === '0' ? 'success' : 'danger'">
            {{ viewForm.status === '0' ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ viewForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewForm.remark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination/index.vue'
import { listUser, getUser, addUser, updateUser, deleteUser, batchDeleteUser, exportUser } from '@/api/user'
import { useRouter } from 'vue-router'

// 加载状态
const loading = ref(false)

// 选中数组
const selectedRows = ref([])

// 总条数
const total = ref(0)

// 用户表格数据
const userList = ref([])

// 弹出层标题
const title = ref('')

// 是否显示弹出层
const open = ref(false)
const viewOpen = ref(false)

// 表单引用
const formRef = ref(null)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phonenumber: '',
  status: ''
})

// 表单参数
const form = reactive({
  userId: null,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  userType: '',
  status: '0',
  password: '',
  remark: ''
})

// 查看表单
const viewForm = reactive({})

// 表单校验规则
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userType: [{ required: true, message: '用户类型不能为空', trigger: 'change' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}

// 获取用户类型标签
function getUserTypeTag(type) {
  const map = {
    '01': 'danger',
    '02': 'warning',
    '03': 'success'
  }
  return map[type] || 'info'
}

// 获取用户类型标签文本
function getUserTypeLabel(type) {
  const map = {
    '01': '管理员',
    '02': '经销商',
    '03': '客户'
  }
  return map[type] || '未知'
}

// 获取用户列表
function getList() {
  loading.value = true
  listUser(queryParams).then(res => {
    console.log('获取用户列表响应:', res) // 添加日志以查看响应格式
    
    // 适应不同的后端返回格式
    if (Array.isArray(res)) {
      // 后端直接返回数组
      userList.value = res
      total.value = res.length
    } else if (res && res.rows) {
      // 后端返回{rows, total}格式
      userList.value = res.rows
      total.value = res.total || res.rows.length
    } else if (res && typeof res === 'object' && res.data) {
      // 后端返回{data: [...]}格式
      if (Array.isArray(res.data)) {
        userList.value = res.data
        total.value = res.data.length
      } else if (res.data.rows) {
        // 后端返回{data: {rows, total}}格式
        userList.value = res.data.rows
        total.value = res.data.total || res.data.rows.length
      }
    } else {
      // 直接使用返回的对象(可能是SysUser列表)
      userList.value = Array.isArray(res) ? res : (res ? [res] : [])
      total.value = userList.value.length
    }
    
    loading.value = false
  }).catch(error => {
    console.error('获取用户列表失败:', error)
    userList.value = []
    total.value = 0
    loading.value = false
  })
}

// 表单重置
function reset() {
  form.userId = null
  form.username = ''
  form.nickname = ''
  form.email = ''
  form.phone = ''
  form.userType = ''
  form.status = '0'
  form.password = ''
  form.remark = ''
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单提交
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 创建一个新的对象来保存要提交的数据，以避免与后端字段不匹配
      const submitData = {
        id: form.userId,  // 后端可能使用id而不是userId
        username: form.username,
        nickname: form.nickname,
        email: form.email,
        phone: form.phone,
        userType: form.userType,
        status: form.status,
        password: form.password,
        remark: form.remark
      }
      
      if (form.userId) {
        // 修改用户
        updateUser(submitData).then(res => {
          console.log('更新用户响应:', res)
          ElMessage.success('修改成功')
          open.value = false
          getList()
        }).catch(error => {
          console.error('修改用户失败:', error)
          ElMessage.error('修改失败: ' + error.message)
        })
      } else {
        // 新增用户
        addUser(submitData).then(res => {
          console.log('新增用户响应:', res)
          ElMessage.success('新增成功')
          open.value = false
          getList()
        }).catch(error => {
          console.error('新增用户失败:', error)
          ElMessage.error('新增失败: ' + error.message)
        })
      }
    }
  })
}

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryParams.userName = ''
  queryParams.phonenumber = ''
  queryParams.status = ''
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedRows.value = selection
}

// 新增按钮操作
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加用户'
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const userId = row.userId || row.id || selectedRows.value[0].userId || selectedRows.value[0].id
  getUser(userId).then(res => {
    console.log('获取用户详情响应:', res) // 添加日志以查看响应格式
    
    // 适应不同的后端返回格式
    let userData = null
    if (res && res.data) {
      userData = res.data
    } else if (typeof res === 'object') {
      userData = res
    }
    
    if (userData) {
      // 确保表单字段与后端返回的字段对应
      form.userId = userData.userId || userData.id
      form.username = userData.username || ''
      form.nickname = userData.nickname || ''
      form.email = userData.email || ''
      form.phone = userData.phone || ''
      form.userType = userData.userType || ''
      form.status = userData.status || '0'
      form.remark = userData.remark || ''
      
      open.value = true
      title.value = '修改用户'
    }
  }).catch(error => {
    console.error('获取用户详情失败:', error)
  })
}

// 查看按钮操作
function handleView(row) {
  const userId = row.userId || row.id
  getUser(userId).then(res => {
    console.log('查看用户详情响应:', res) // 添加日志以查看响应格式
    
    // 适应不同的后端返回格式
    let userData = null
    if (res && res.data) {
      userData = res.data
    } else if (typeof res === 'object') {
      userData = res
    }
    
    if (userData) {
      // 确保视图表单字段与后端返回的字段对应
      viewForm.userId = userData.userId || userData.id
      viewForm.username = userData.username || ''
      viewForm.nickname = userData.nickname || ''
      viewForm.email = userData.email || ''
      viewForm.phone = userData.phone || ''
      viewForm.userType = userData.userType || ''
      viewForm.status = userData.status || '0'
      viewForm.createTime = userData.createTime || ''
      viewForm.remark = userData.remark || ''
      
      viewOpen.value = true
    }
  }).catch(error => {
    console.error('查看用户详情失败:', error)
  })
}

// 删除按钮操作
function handleDelete(row) {
  const ids = row.userId || row.id || selectedRows.value.map(item => item.userId || item.id).join(',')
  
  ElMessageBox.confirm('是否确认删除用户编号为"' + ids + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    deleteUser(ids).then(res => {
      console.log('删除用户响应:', res)
      ElMessage.success('删除成功')
      getList()
    }).catch(error => {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败: ' + error.message)
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 批量删除操作
function handleBatchDelete() {
  const ids = selectedRows.value.map(item => item.userId || item.id).join(',')
  
  ElMessageBox.confirm('是否确认删除选中的' + selectedRows.value.length + '条数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    batchDeleteUser(ids).then(res => {
      console.log('批量删除响应:', res)
      ElMessage.success('批量删除成功')
      getList()
    }).catch(error => {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败: ' + error.message)
    })
  }).catch(() => {
    // 用户取消操作
  })
}

// 导出操作
function handleExport() {
  ElMessageBox.confirm('是否确认导出所有用户数据?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    exportUser(queryParams).then(res => {
      // 处理二进制流文件下载
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = '用户数据.xlsx'
      link.click()
      URL.revokeObjectURL(link.href)
      ElMessage.success('导出成功')
    })
  }).catch(() => {})
}

// 导入操作
function handleImport() {
  ElMessage.success('导入操作')
}

// 语音转文字操作
function goToVoiceToText() {
  // 跳转到语音转文字页面
  const router = useRouter()
  router.push('/voice/to-text')
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.table-wrapper {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  text-align: center;
}
</style> 